<script>
import {addOrUpdateAudio} from "@/api/aihuman/mySources/audio";
import {getUrl} from "@/util/aihuman/getUrl";

export default {
  name: "EditAudioDialog",
  data() {
    return {
      dialogVisible: false,
      rowData: {},
      rules: {
        name: [
          {required: true, message: '请输入素材名称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    getUrl,
    saveData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          addOrUpdateAudio(this.rowData).then(res => {
            this.$message.success(res.data.msg)
            this.closeDialog()
            this.$emit('save-ok')
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(data) {
      this.dialogVisible = true
      this.rowData = data
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    closeDialog() {
      this.dialogVisible = false
      this.$refs.audioRef.pause()
      this.$refs.audioRef.currentTime = 0
    },
    formatFileSize(bytes) {
      const KB = 1024;
      const MB = KB * 1024;

      if (bytes >= MB) {
        return (bytes / MB).toFixed(2) + ' MB';
      } else if (bytes >= KB) {
        return (bytes / KB).toFixed(2) + ' KB';
      } else {
        return bytes + ' Bytes';
      }
    }

  }
}
</script>

<template>
  <el-dialog
    title="信息编辑"
    :visible.sync="dialogVisible"
    width="700px"
    append-to-body
    :close-on-click-modal="false"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="video-box">
          <audio ref="audioRef" :src="getUrl() + rowData.url" controls></audio>
        </div>
      </el-col>
      <el-col :span="12">
        <el-form ref="form" :model="rowData" :rules="rules" label-width="80px">
          <el-form-item label="素材名称" prop="name">
            <el-input v-model="rowData.name"></el-input>
          </el-form-item>
          <el-form-item label="素材大小">
            {{ formatFileSize(rowData.fileSize) }}
          </el-form-item>
          <el-form-item label="素材格式">
            {{ rowData.extension }}
          </el-form-item>
          <el-form-item label="上传时间">
            {{ rowData.createTime }}
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="saveData">确 定</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.video-box {
  width: 100%;
  background: #fafafa;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
